package com.borrowing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.borrowing.entity.Result;
import com.borrowing.entity.pojo.User;
import com.borrowing.entity.pojo.UserFollow;
import com.borrowing.entity.pojo.dto.FollowDto;
import com.borrowing.entity.pojo.dto.QueryDto;
import com.borrowing.mapper.UserFollowMapper;
import com.borrowing.mapper.UserMapper;
import com.borrowing.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserFollowMapper userFollowMapper;


    /**
     * 添加新用户
     * @param userName
     * @return
     */
    @Override
    public Result registration(String userName) {
        if(userName.length() >= 8){
            return Result.fail("昵称不可以超过8位");
        }
        int count = userMapper.selectByName(userName);
        if(count >= 1){
            return Result.fail("您输入的昵称已存在，请重新输入");
        }
        else{
            User user = new User();
            user.setUserName(userName);
            userMapper.insert(user);
            return Result.ok();
        }
    }

    @Override
    public Result follow(FollowDto followDto) {
        if(followDto.getFollowId() == null || followDto.getUserId() == null){
            return Result.fail("参数不可以为空");
        }
        Integer userId = followDto.getUserId();
        Integer followId = followDto.getFollowId();
        User user = userMapper.selectById(userId);
        if(user == null){
            return Result.fail("用户为空,请注意是否有这个用户");
        }
        User followUser = userMapper.selectById(followId);
        if(followUser == null){
            return Result.fail("粉丝id为空,请注意是否有这个用户");
        }
        if(userId.equals(followId)){
            return Result.fail("不可以自己关注自己喔");
        }
        LambdaQueryWrapper<UserFollow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserFollow::getFollowId,followId)
                        .eq(UserFollow::getUserId,userId);
        List<UserFollow> userFollows = userFollowMapper.selectList(lambdaQueryWrapper);
        if(!userFollows.isEmpty()){
            return Result.fail("已经关注啦");
        }
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowId(followId);
        userFollow.setUserId(userId);
        userFollowMapper.insert(userFollow);
        return Result.ok();
    }

    @Override
    public Result<List<User>> queryUser(QueryDto queryDto) {
        List<User> list = userMapper.selectAll(queryDto);
        return Result.ok(list);
    }
}
